

"""8.1 RESTful API基础与环境安装"""
from django.views.generic import TemplateView
from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.views import APIView

from common.http_util import Result


# 定义一个视图类，继承自APIView：使用postman调用接口
class HelloApi(APIView):
    def get(self, request):
        print(" 调用 Django restfull api 接口：get方法=========")
        #定义一个字典
        data = {"title": "Python web", "content": "Python web is very good"}
        return Response(data, status=200)


'''8.2 API接口GET请求及参数解析'''
class GetParserParam(APIView):
    def get(self, request):
        print(" 调用 Django restfull api 接口：get方法=========")
        print("request: ",request)
        #获取get参数
        params = request.query_params
        print(" request.query_params: ",params)
        print(params.get("title"))
        print(params.get("content"))
        print("request.data: ",request.data)
        print("request.method: ",request.method)
        print("request.path: ",request.path)
        print("request.path_info: ",request.path_info)
        #打印出头部信息
        print("request.headers: ",request.headers)
        print("request.headers.get('User-Agent'): ",request.headers.get('User-Agent'))
        print("request.headers.get('Content-Type'): ",request.headers.get('Content-Type'))

        return Response(params, status=200)

'''8.3 API接口POST请求及参数解析'''
class PostParserParam(APIView):
    def post(self, request):
        print(" 调用 Django restfull api 接口：post方法=========")
        print("request: ",request)
        #获取post参数 ...
        print("数据体：request.data: ",request.data)
        print("数据体：request.data.get('title'): ",request.data.get('title'))
        print("request.method: ",request.method)
        print("request.path: ",request.path)
        print("============遍历数据体============")
        for key,value in request.data.items():
            print("==key: ",key," value: ",value)
        print("request.method: ", request.method)
        print("request.path: ", request.path)
        print("request.path_info: ", request.path_info)
        # 打印出头部信息
        print("request.headers: ", request.headers)
        print("request.headers.get('User-Agent'): ", request.headers.get('User-Agent'))
        print("request.headers.get('Content-Type'): ", request.headers.get('Content-Type'))

        return Response(request.data, status=200)


'''8.4 API接口响应结果数据封装'''
class ResponseDataFormat(APIView):
    def post(self, request):
        print(" 调用 Django restfull api 接口：post方法=========")
        print("request: ",request)
        #标准化输出对象
        result=Result(200,"success",request.data)
        print("result: ",result)
        return Response(result,200)


'''8.5 序列化与反序列化深度应用'''
class ArticleSerializer(serializers.Serializer):
    title = serializers.CharField(max_length=32)
    content = serializers.CharField()
    price = serializers.IntegerField()

class ArticleForm(APIView):
    def post(self, request):
        print("打印出请求的信息：",request)
        """数据序列化验证"""
        serializers = ArticleSerializer(data=request.data)
        if serializers.is_valid():
            print("数据验证通过：",serializers.data)
            result = Result(200,"success",serializers.data)
            return Response(result,200)
        else:
            print("数据验证失败：",serializers.errors)
            result = Result(400,"error",serializers.errors)
            return Response(result,400)


from blog.sqlalchemy_model import *
'''8.6 API接口数据与前端异步交互案例'''
class ArticleView(TemplateView):
    template_name = 'blog/article_from_api.html'

#创建API数据
class ArticleList(APIView):
    def get(self, request):
        print(" 调用 Django restfull api 接口：get方法=========")
        # 查询数据库表中的所有数据（blog_article)
        articles = session.query(Article).all()
        # 数据库session关闭
        session.close()
        #对象序列化
        list=[]
        for article in articles:
            list.append({"id":article.id,"title":article.title,"content":article.content,"price":article.price,"pub_date":article.pub_date,"status":article.status})

        result = Result(200, "success", list)
        # 序列化数据
        return Response(result, 200)

